<template>
  <div class="admin-container">
    <!-- 侧边 -->
    <div class="admin-sidebar">
      <!-- 网点集 -->
      <div class="area-tree-section box-border-style">
        <div class="tl-corner"></div>
        <div class="tr-corner"></div>
        <div class="bl-corner"></div>
        <div class="br-corner"></div>
        <div class="tree-search">
          <div>
          <el-select @change="organChangeEvent" v-model="organId" placeholder="请选择" value-key="item">
            <el-option v-for="item in organOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          </div>
          <div style="margin-top:0.1rem">
          <el-button type="primary" @click="getExcel()" icon="el-icon-upload2" size="medium">导出用电数据</el-button>
          <el-button type="primary" @click="setworktime()" icon="el-icon-time" size="medium">设置上班时间</el-button>
       </div>
        </div>
        <div style="height:9.04rem">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">

            <el-tree :data="FilialeOrganAreaData" :props="treeProps" :expand-on-click-node="false" highlight-current
              node-key="id" @node-click="onClickTreeNode" ref="filialeOrganAreaTree">
              <span slot-scope="{ data }" @drop="drop(data, $event)" @dragover="dragover_handler($event)"
                style="position: relative">
                <span style="
                    vertical-align: middle;
                    margin-right: 0.1rem;
                    cursor: pointer;
                  ">{{ data.name }}</span>
                <!-- -->
                <span
                  title="设备阈值"
                  class="downExcel"
                  @click.stop="getProThreshold(data.id)"
                  style="display: inline-block;
                  position: absolute;
                  width: 0.18rem;
                  height: 0.18rem;"
                  v-if="data.type == 'area'"
                ><i class="el-icon-tickets" style="font-size: 0.18rem;"></i>
                </span>
                <!-- <div
                  class="updata-btn"
                  @click.stop="host_updata(data.id, data.organId)"
                  v-if="
                    data.hosts.length > 0 &&
                    data.type == 'area' &&
                    usermanager == 2
                  "
                >
                  <img src="@/assets/icons/host_updata.png" />
                </div> -->
                <!-- <div
                  v-if="data.hostNum > 0"
                  style="
                    display: inline-block;
                    position: absolute;
                    width: 0.18rem;
                    height: 0.18rem;
                  "
                >
                  <div style="position: relative" title="网关">
                    <img
                      src="@/assets/icons/host2.png"
                      alt=""
                      style="width: 100%; height: 100%"
                    />
                    <span
                      style="
                        position: absolute;
                        top: -3px;
                        right: -5px;
                        font-size: 0.1rem !important;
                        color: #33dedb;
                      "
                      >{{ data.hostNum }}</span
                    >
                  </div>
                </div> -->
                <!-- <div
                  v-if="data.probeMun> 0"
                  style="
                    display: inline-block;
                    position: absolute;
                    margin-left: 0.26rem;
                    width: 0.18rem;
                    height: 0.18rem;
                  "
                >
                  <div style="position: relative" title="用电器">
                    <img
                      src="@/assets/icons/electrical-appliances.png"
                      alt=""
                      style="width: 100%; height: 100%"
                    />
                    <span
                      style="
                        position: absolute;
                        top: -3px;
                        right: -5px;
                        font-size: 0.1rem !important;
                        color: #33dedb;
                      "
                      >{{ data.probeMun}}</span
                    >
                  </div>
                </div> -->
              </span>
            </el-tree>
          </el-scrollbar>
        </div>
      </div>

      <!-- </el-scrollbar> -->
    </div>
    <!-- 主体 -->
    <div class="admin-main" v-if="this.$store.getters.isMap">
      <div class="content-top">
        <div class="map-section">
          <admin-map v-if="this.$store.getters.isMap" ref="child" :data="mapData"
            @showOrganDetail="showOrganDetailEvent"></admin-map>
          <!-- <div class="yansi-data-table">
         <el-scrollbar style="height: 100%">
            <el-table
              :data="tableData2"
              style="width: 100%"
              align="center"
              row-key="id"
              border
              lazy
             
              :load="load"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              @cell-click="showPTable2"
            >
              <el-table-column label="网点" prop="outlets" align="center" >
              </el-table-column>
              <el-table-column label="区域" prop="region" align="center"  >
                	<template slot-scope="scope">
                    <div class="quyue_tbn" @click="cilkerow(scope.row)">{{scope.row.region}}</div>
                    </template>
              </el-table-column>
         
              <el-table-column label="设备数统计" align="center">
                <el-table-column label="总数" prop="total" align="center" >
                </el-table-column>
                <el-table-column label="电灯" prop="dd" align="center"  >
                </el-table-column>
                <el-table-column
                  label="空调"
                  prop="kt"
                  align="center"
               
                >
                </el-table-column>
                <el-table-column
                  label="插座"
                  prop="qt"
                  align="center"
               
                >
                </el-table-column>
                <el-table-column
                  label="吊扇"
                  prop="ds"
                  align="center"
               
                >
                </el-table-column>
              </el-table-column>
        
            </el-table>
          </el-scrollbar>
      </div> -->
          <!--<user-operation v-else :organId="organId"></user-operation>-->
        </div>
      </div>
      <!-- 底部图表 -->
      <div class="content-bottom">
        <!--设备数统计-->
        <div class="probe-number-chart">
          <probes-number-pie-chart :pieChartData="probesNumberPieChartData"></probes-number-pie-chart>
          <div class="tl-corner"></div>
          <div class="tr-corner"></div>
          <div class="bl-corner"></div>
          <div class="br-corner"></div>
        </div>
        <!-- 电器数统计 -->
        <div class="electric-appliance-chart">
          <electric-appliances-number-pie-chart :pieChartData="electricAppliancesNumberPieChartData">
          </electric-appliances-number-pie-chart>
          <div class="tl-corner"></div>
          <div class="tr-corner"></div>
          <div class="bl-corner"></div>
          <div class="br-corner"></div>
        </div>
        <!--用电量统计-->
        <div class="electricity-quantity-chart">
          <electric-quantity-bar-chart :barChartData="electricQuantityBarChartData"></electric-quantity-bar-chart>
          <div class="tl-corner"></div>
          <div class="tr-corner"></div>
          <div class="bl-corner"></div>
          <div class="br-corner"></div>
        </div>
        <!--<div class="appliance-runtime-section box-border-style">
          <appliance-run-time></appliance-run-time>
        </div>-->
        <!-- div class="appliance-switchtimes-section box-border-style">
					<appliance-switchs></appliance-switchs>
				</div> -->
      </div>
    </div>
    <div v-else>
      <div v-if="!aerialview" class="aerialview-row">
        <el-tabs v-model="aerialviewvalue" type="border-card">
          <el-tab-pane label="设备控制" name="1">
            <aerial-view></aerial-view>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-else class="area-plan-wrap">
        <updata-host ref="updataHost" :hostid="hostid" :organId="organId" v-if="updatastate"></updata-host>
         <prod-threshold ref="ProdThreshold" :areaid="areaid" v-if="prothreshold"></prod-threshold>

        <area-plan ref="areaPlan" :area="area" @Selecttree="Selecttree" v-if="!prothreshold&&!updatastate"></area-plan>
        <!-- <area-plan ref="areaPlan" :area="area"></area-plan> -->
      </div>
    </div>
    <div class="alarm-event-button" @mousedown.stop="ShowAlarmistEvent" :style="{
      backgroundColor: isShowAlarm ? 'rgba(0,0,0,0.5)' : 'rgba(98,1,25,0.51)',
    }">
      <img :src="
        isShowAlarm
          ? require('@/assets/icons/alarm-data-white.png')
          : require('@/assets/icons/alarm-data-red.png')
      " alt="" />
      <span>当前异常用电器</span>
    </div>
    <!-- 报警表格弹窗	-->
    <div class="Warning-furniture alarm-event-dialog">
      <el-dialog title="当前异常用电器" :visible.sync="dialogTableVisible">
        <el-table :data="alarmTableData">
          <el-table-column property="name" label="电器名称"></el-table-column>
          <el-table-column property="address" label="电器位置">
          </el-table-column>
          <el-table-column property="status" label="异常类型">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div style="
                  color: #44c7f4;
                  height: 100%;
                  width: 100%;
                  cursor: pointer;
                " @mousedown.stop="goCurrentAlarmPage(scope.row.id)">
                查看
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <el-dialog class="edit-probe-dia" title="设置上班时间" :visible.sync="dialogwroktimeVisible" width="550px"
      @close="resetForm" :close-on-click-modal="false">
      <div class="SetTime-row">
        <!-- <div class="SetTime-title">工作时段</div> -->
        <div v-if="OpenTimeArr != ''">
          <div class="SetTime-boxmian" v-for="(item, index) in OpenTimeArr" :key="index">
            <div>
              <el-checkbox-group v-model="item.dayType">
                <el-checkbox v-for="item in Defaultoptionslist" :key="item.dayType" :label="item.dayType">
                  {{ item.dayName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="SetTime-box">
              <el-time-picker v-model="item.startTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择开始日期时间">
              </el-time-picker>

              <span>~</span>
              <el-time-picker v-model="item.endTime" value-format="HH:mm:ss" format="HH:mm:ss" placeholder="选择结束日期时间"
                :picker-options="{
                  selectableRange: `${item.startTime ? item.startTime + ':00' : '00:00:00'
                    }-23:59:59`,
                }">
              </el-time-picker>

              <span class="el-icon-remove-outline" @click="deleteItem('Optime', index)"></span>
            </div>

          </div>
        </div>
        <div class="SetTime-addBtn">
          <span style="color:#fff" class="el-icon-circle-plus-outline" @click="addNew('Optime')"></span>
        </div>
        <div class="SetTimeSubmitBtn">
          <el-button type="primary" @click="SetTimeSubmitBtn">
            提交
          </el-button>
        </div>
      </div>
    </el-dialog>


    <!-- 导出数据筛选	-->
    <el-dialog class="Excel-dia" title="导出用电数据" :visible.sync="dialogExcelVisible" width="550px" @close="resetForm"
      :close-on-click-modal="false">
      <div class="Excel-row">
        <div class="Excel-box">
          <div class="Excel-title">导出类型</div>
          <div>
            <el-select v-model="getExceltype" clearable placeholder="请选择">
              <el-option v-for="item in Exceltypelist" :key="item.value" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="Excel-box">
          <div class="Excel-title">导出时间</div>
          <div>
            <el-date-picker   v-if="getExceltype == 1" v-model="getExceltime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd">
            </el-date-picker>
            <el-date-picker
              v-model="getExcelmonth"
              type="month"
              value-format="M"
              format="M月"
              v-if="getExceltype == 0"
              placeholder="选择月">
            </el-date-picker>
          </div>
        </div>
        <div class="Excel-box">
          <div class="Excel-title">设备类型</div>
          <div>
            <el-select  v-if="getExceltype == 0" v-model="getExcelradio" placeholder="请选择设备类型">
              <el-option
              v-for="item in channelTargetCategory"
                          :key="item.code"
                          :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
            <el-checkbox-group v-model="checkList"  v-if="getExceltype == 1">
              <el-checkbox v-for="item in channelTargetCategory" :key="item.code" :label="item.code">
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="Excel-box" v-if="getExceltype == 1">
          <div class="Excel-title">区域选择</div>
          <div style="flex: 1">
            <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 200px">
              <el-tree :data="FilialeAreaData" :props="treeProps" show-checkbox :check-strictly="true"
                :expand-on-click-node="false" node-key="id" ref="filialeAreaTree">
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
        <div class="SetTimeSubmitBtn">
          <el-button type="primary" @click="ExcelSubmitBtn"> 提交 </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ajax from "@/utils/ajax";
import AdminMap from "./components/AdminMap.vue";
// import DeviceStatistics from './components/DeviceChartStatistics.vue'
// import UserOperation from './components/UserOperation.vue'
// import ApplianceStatistics from './components/ApplianceChartStatistics.vue'
// import ApplianceRunTime from './components/ApplianceChartRunTime.vue'
// import ApplianceSwitchs from './components/ApplianceChartSwitchs.vue'
import AreaPlan from "./components/AdminAreaPlan.vue";
import ProbesNumberPieChart from "@/pages/admin/components/ProbeNumberPieChart";
import ElectricAppliancesNumberPieChart from "@/pages/admin/components/ElectricAppliancesNumberPieChart";
import ElectricQuantityBarChart from "@/pages/admin/components/ElectricQunantityBarChart";
import UpdataHost from "./components/UpdataHost.vue";
import ProdThreshold from "./components/ProdThreshold.vue";
import AerialView from "./components/AerialView/AerialView.vue";
let dictProbeKindList = [

  {
    code: 801,
    probeCategoryCode: "Z",
    name: "吊扇",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 701,
    probeCategoryCode: "Y",
    name: "充电桩",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 601,
    probeCategoryCode: "D",
    name: "中央空调控制器",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 402,
    probeCategoryCode: "N",
    name: "智能空调控制器",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 401,
    probeCategoryCode: "N",
    name: "智能空调伴侣",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  // {
  //   code: 301,
  //   probeCategoryCode: "M",
  //   name: "红外遥控器",
  //   channelNum: 8,
  //   enabled: 1,
  //   bindIcon: 1,
  //   bindMold: 1,
  // },
  {
    code: 202,
    probeCategoryCode: "K",
    name: "智能计量插座",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 201,
    probeCategoryCode: "K",
    name: "智能插座",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 110,
    probeCategoryCode: "S",
    name: "智能导轨开关",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 104,
    probeCategoryCode: "S",
    name: "四开开关",
    channelNum: 4,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 103,
    probeCategoryCode: "S",
    name: "三开开关",
    channelNum: 3,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 102,
    probeCategoryCode: "S",
    name: "双开开关",
    channelNum: 2,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
  {
    code: 101,
    probeCategoryCode: "S",
    name: "单开开关",
    channelNum: 1,
    enabled: 1,
    bindIcon: 1,
    bindMold: 1,
  },
];
export default {
  components: {
    AdminMap,
    // UserOperation,
    // DeviceStatistics,
    // ApplianceStatistics,
    // ApplianceRunTime,
    // ApplianceSwitchs,
    AreaPlan,
    ProbesNumberPieChart,
    ElectricAppliancesNumberPieChart,
    // eslint-disable-next-line vue/no-unused-components
    UpdataHost,
    ElectricQuantityBarChart,
    AerialView,
    ProdThreshold
  },
  data() {
    return {
      customerId: null,
      organGatherId: null,
      organId: null,
      area: {},
      dialogTableVisible: false,
      isOrganGather: true,
      probesNumberPieChartData: [],
      electricAppliancesNumberPieChartData: [],
      electricQuantityBarChartData: [],

      treeAreaGathereData: [],
      FilialeOrganAreaData: [], // 主页左边的网点集、网点、区域树数据
      treeProps: {
        children: "children",
        label: "name",
      },
      alarmTableData: [
        { name: "电器名称", address: "电器位置", status: "异常类型", id: 21 },
      ],
      isMap: true,
      mapData: null,
      isShowAlarm: true,
      data: {},
      defaultProps: {
        children: "children",
        label: "text",
      },
      filterText: "",

      deviceStatisticsData: null,
      applianceStatisticsData: null,
      updatastate: false,
      hostid: -1,

      //
      prothreshold:false,
      areaid:-1,
      usermanager: this.$store.getters.user.manager,
      dialogwroktimeVisible: false,
      OpenTimeArr: [
        { endTime: "08:30", startTime: "07:00", dayType: [1, 2, 3, 4] },
        { endTime: "14:30", startTime: "14:00", dayType: [] },
      ],
      settimeid: -1,
      settimetype: -1,
      Defaultoptionslist: [],
      aerialview: true,
      aerialviewvalue: '1',
      organOptions: [],

      //导出数据
      dialogExcelVisible: false,
      getExceltype: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      Exceltypelist: [
        { name: "导出网点", value: 0 },
        { name: "导出区域", value: 1 },
      ],
      getExceltime: [],
      channelTargetCategory: [],
      checkList: [],
      getExcelmonth:'',
      getExcelradio:null,
    };
  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
  },
  created() {
    this.$store.dispatch("actions/setisMapAction", true);
    this.customerId = this.$store.getters.customerId;
    this.getTargetCategoryData();
    this.getOrganListData();
    this.getCustomerAvailableData()
    this.getExceltime.push(getFormatDate(new Date().getTime() - 24 * 60 * 60 * 1000 * 2).slice(0,10))
    this.getExceltime.push(getFormatDate(new Date().getTime() - 24 * 60 * 60 * 1000).slice(0,10))
  },
  methods: {
    //获取日期类型
    getCustomerAvailableData() {
      ajax.get({
        url: this.$API.getCustomerAvailableList,
        success: (response) => {

          if (response.success) {
            this.$nextTick(() => {
              this.Defaultoptionslist = response.data
            })
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },

    //根据网点获取用电量统计数据
    getFilialeElectricQuantity(data) {
      let self = this;
      let geturl
      if (self.$store.getters.user.manager == 2) {
        geturl = self.$API.getFilialeElectricQuantity
      }
      else {
        geturl = self.$API.getElectricityQuantityStatisticByUserId
      }
      ajax.post({
        url: geturl,
        data: {
          id: data.id,
          filialeOrOrgan: data.type,
        },
        success: (res) => {
          // console.log('用电量数据', res.data)
          this.electricQuantityBarChartData = res.data;
        },
        error: (err) => {
          self.$message.error(err.message);
          console.log(err);
        },
      });
    },
    // 根据网点获取电器数量统计数据
    getFilialeHostsNumber(data) {
      let self = this;
      let obj = { id: data.id, type: data.type };
      let geturl
      if (self.$store.getters.user.manager == 2) {
        geturl = "/shike3k/user/webrest/v3.3/electricity/web/filiale/electric_category_count/query"
      }
      else {
        geturl = this.$API.queryElectricCategoryCountByUserId
      }
      ajax.post({
        //url: "/shike3k-user/webrest/v3.3/electricity/web/filiale/electric_category_count/query",
        url: geturl,
        data: obj,
        success: (res) => {
          this.electricAppliancesNumberPieChartData = res.data;
        },
        error: (err) => {
          self.$message.error(err.message);
          console.log(err);
        },
      });
    },
    //根据网点获取探头数量统计数据
    getFilialeProbesNumber(data) {
      let self = this;
      let obj = (obj = { id: data.id, type: data.type });
      let geturl
      if (self.$store.getters.user.manager == 2) {
        geturl = "/shike3k/user/webrest/v3.3/electricity/web/filiale/device_count_by_filter/get"
      }
      else {
        geturl = this.$API.getDeviceCountByUserId
      }
      ajax.post({

        //url: "/shike3k-user/webrest/v3.3/electricity/web/filiale/device_count_by_filter/get",
        url: geturl,
        data: obj,
        success: (res) => {
          this.probesNumberPieChartData = res.data;
        },
        error: (err) => {
          self.$message.error(err.message);
          console.log(err);
        },
      });
    },
    // 点击网点集时需要处理的地图数据
    handlerOnClickFiliale(data, organChildren) {
      let children = data.children;
      if (children.length > 0) {
        children.forEach((item) => {
          if (item.type === "organ") {
            let flag = false;
            organChildren.forEach((i) => {
              if (i.id === item.id) {
                flag = true;
              }
            });
            if (!flag) {
              organChildren.push(item);
            }
          } else {
            this.handlerOnClickFiliale(item, organChildren);
          }
        });
      }
    },
    ShowAlarmistEvent() {
      this.dialogTableVisible = true;
    },
    goCurrentAlarmPage(id) {
      this.dialogTableVisible = false;
      this.data.type = "area";
      this.data.id = id;
      this.$refs.filialeOrganAreaTree.setCurrentKey(id);
      this.$store.dispatch("actions/setisMapAction", true);
      setTimeout(() => {
        this.area = this.data;
        this.$store.dispatch("actions/setisMapAction", false);
      }, 1);
    },
    // 点击树节点
    onClickTreeNode(data) {
      console.log(data);
      this.$store.dispatch("actions/setAreatitleAction", data.name);
      if (data.type === "area") {
        this.$store.dispatch("actions/setisMapAction", true);
        this.$store.dispatch(
          "actions/setfilialeAction",
          getParents(this.FilialeOrganAreaData, data.id).slice(-2)[0]
        );

        setTimeout(() => {
          this.area = data;

          this.$store.dispatch("actions/setisMapAction", false);
          this.updatastate = false;
          this.prothreshold=false
        }, 1);
      } else {
        this.$store.dispatch("actions/setisMapAction", true);

        this.mapData = data.hosts;
        this.getFilialeProbesNumber(data);
        this.getFilialeHostsNumber(data);
        //this.getFilialeElectricQuantity(data);

        this.$nextTick(() => {
          this.$refs.child.setMapData();
        });
        this.$store.dispatch("actions/setfilialeAction", data.id);
        if (data.type === "filiale") {
          this.isOrganGather = true;
        } else {
          this.isOrganGather = false;
        }
        this.getChartData(data.id);
      }
    },
    // //点击升级
    getProThreshold(id) {
      console.log(id)
      this.$store.dispatch("actions/setisMapAction", false);
       this.areaid = id;
      this.prothreshold = true;
     

      this.$refs.filialeOrganAreaTree.setCurrentKey(id);
    },

    // //点击升级
    host_updata(id, organId) {
      this.$store.dispatch("actions/setisMapAction", false);
      this.updatastate = true;
      this.hostid = id;
      this.organId = organId;

      this.$refs.filialeOrganAreaTree.setCurrentKey(id);
    },
    // 获取网点列表
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.$store.getters.user.id,
        success: (response) => {
          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            this.organId = resp[0].id
            this.queryFilialeByCustomerId()
          } else {
            this.organOptions = [];
          }
        },
        error: (res) => {

          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    organChangeEvent() {
      this.queryFilialeByCustomerId()
    },
    // 获取网点列表
    queryFilialeByCustomerId() {

      ajax.get({
        url: this.$API.getUserAreaTreeByOrganId + this.organId,
        success: (response) => {
          const resp = this.setNodeKey(response.data)
          this.FilialeOrganAreaData = resp;
          this.onClickTreeNode(resp[0]);
          this.$nextTick(() => {
            this.$refs.filialeOrganAreaTree.setCurrentKey(resp[0].id);
          });
        },
      });
    },

    // 获取网点集下的主机列表
    getFilialeHost() {
      let currentNode = this.$refs.refDeviceTree.getCurrentNode();
      ajax.post({
        url: this.$API.getFilialeHost,
        data: {
          customerId: this.customerId,
          id: currentNode.id,
        },
        success: (response) => {
          const resp = response.rs.rows;
          this.mapData = resp;
          this.$refs.child.setMapData();
          console.log("获取网点集下所有的主机", resp);
        },
      });
    },

    // 获取网点集数据
    getOrganGatherData() {
      ajax.post({
        url: this.$API.getOrganGather,
        data: { customerId: this.customerId },
        success: (response) => {
          const resp = response.data;
          this.treeAreaGathereData = resp;
          if (resp.length > 0) {
            this.organGatherId = resp[0].id;
            this.getChartData(resp[0].id);
            // this.getOrganData()
          }
        },
      });
    },
    // 获取图表数据
    getChartData(id) {
      let po_data = {};
      if (this.isOrganGather) {
        po_data = { id: id, type: 1 };
      } else {
        po_data = { organId: id, type: 2 };
      }
      // 获取安装设备数统计
      ajax.post({
        url: this.$API.getHostStatistics,
        data: po_data,
        success: (response) => {
          //console.log(response)
          const resp = response.data;
          this.setDeviceStatisticsData(resp);
        },
      });
      // 获取电器数统计
      ajax.post({
        url: this.$API.getAapplianceCount,
        data: po_data,
        success: (response) => {
          const resp = response.data;
          this.setApplianceStatisticsData(resp);
        },
      });
    },
    // 获取网点列表，设置地图坐标
    // getOrganData() {
    // 	let po_id = this.organGatherId
    // 	ajax.post({
    // 		url: this.$API.getOrganByFilialeId,
    // 		data: { id: po_id },
    // 		success: (response) => {
    // 			this.mapData = response.data.records
    // 		},
    // 	})
    // },
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    },
    // 点击树节点
    handleNodeClick(nodeData) {
      if (nodeData.attribute.type === "organ") {
        // 网点
        this.isOrganGather = false;
        this.organId = nodeData.id;
        this.$store.dispatch("actions/setisMapAction", false);
      } else {
        // 网点集
        this.isOrganGather = true;
        this.$store.dispatch("actions/setisMapAction", true);
        this.organGatherId = nodeData.id;
        this.getFilialeHost();
        // this.getOrganData()
        // 待页面地图组件加载完成之后，再加载地图
        this.$nextTick(() => {
          this.$refs.child.setMapData();
        });
      }
      this.getChartData(nodeData.id);
    },

    // 点击主页跳转地图页面
    changeMain() {
      this.handleNodeClick(this.treeAreaGathereData[0]);
      this.$refs.refDeviceTree.setCurrentNode(this.treeAreaGathereData[0]);
    },

    // 安装设备数统计
    setDeviceStatisticsData(data) {
      let dataArr = [];
      for (let item of data) {
        let obj = {};
        obj.name = item.name;
        obj.value = item.count;
        dataArr.push(obj);
      }
      let dataObj = {};
      if (data.length === 0) {
        dataObj.title = "暂无相关统计数据";
      } else {
        dataObj.title = "安装设备数统计";
      }

      dataObj.data = dataArr;
      this.deviceStatisticsData = dataObj;
    },

    // 安装电器数统计
    setApplianceStatisticsData(data) {
      let dataArr = [];
      for (let item of data) {
        let obj = {};
        obj.name = item.name;
        obj.value = item.count;
        dataArr.push(obj);
      }
      let dataObj = {};
      if (data.length === 0) {
        dataObj.title = "暂无相关统计数据";
      } else {
        dataObj.title = "安装电器数统计";
      }

      dataObj.data = dataArr;
      this.applianceStatisticsData = dataObj;
    },
    Selecttree(value) {
      console.log(value);
      this.$refs.filialeOrganAreaTree.setCurrentKey(value);
    },
    // 地图
    showOrganDetailEvent(value) {
      this.organId = value;
      this.$store.dispatch("actions/setisMapAction", false);
      this.getChartData(value);
    },
    //设置
    resetForm() {
      this.dialogProbeVisible = false;

      // for(let i of this.LockTimeArr){
      // if (i.startTime == '' || i.endTime == '') {
      // 	self.$message({
      // 		message: '开始或结束时间不能为空',
      // 		type: 'warning',
      // 	})
      // 	return
      // } else if (!regex.test(i.startTime) || !regex.test(i.endTime)) {
      // 	self.$message({
      // 		message: '时间错误',
      // 		type: 'warning',
      // 	})
      // } else {
      // 	po_LockTimeArr.push(i.startTime + '-' + i.endTime)
      // }
      // }
      // self.pojoProbe.LockTime=po_OpenTimeArr
      // self.pojoProbe.LockTime=po_LockTimeArr
    },
    //设置上班时间  
    setworktime() {
      let self = this
      this.dialogwroktimeVisible = true
  
      this.OpenTimeArr = []
     
        ajax.get({
          url: this.$API.getOrganWorkingTime + self.organId,
          success: (response) => {
            if (response.data.length > 0) {
              for (let item of response.data) {
                let OpenTimeattr = {}
                OpenTimeattr.startTime = item.startTime
                OpenTimeattr.endTime = item.endTime
                OpenTimeattr.dayType =item.dayTypeList
                OpenTimeattr.dayTypeList =item.dayTypeList
                self.OpenTimeArr.push(OpenTimeattr)

              }
            }
            else {
              self.OpenTimeArr = [
                { endTime: "", startTime: "", dayType: [] },
                { endTime: "", startTime: "", dayType: [] },
              ]
            }
            // console.log(response)  
          },
        })

     

    },
    //提交
    SetTimeSubmitBtn() {
      let self = this;
      let regex = /^(([0-2][0-3])|([0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/; //正则表达式格式xx:xx 第一位为最大值为00-23 第二位00 - 59
      let po_OpenTimeArr = [];
      let po_LockTimeArr = [];
      let SetTimearr = []
      if (this.OpenTimeArr.length == 0) {
        self.$message({
          message: "未填写时间",
          type: "warning",
        });
        return;
      }
      for (let i of this.OpenTimeArr) {
        if (i.startTime == "" || i.endTime == "") {
          self.$message({
            message: "开始或结束时间不能为空",
            type: "warning",
          });
          return;
        } else if (!regex.test(i.startTime) || !regex.test(i.endTime)) {
          self.$message({
            message: "时间错误",
            type: "warning",
          });
          return;
        }
        else if (i.dayType.length == 0) {
          self.$message({
            message: "类型不能为空  ",
            type: "warning",
          });
          return;
        }
        else {
          let SetTimeattr = {}
          SetTimeattr.startTime = i.startTime
          SetTimeattr.endTime = i.endTime
          SetTimeattr.dayType = "," + i.dayType.join(',') + ","
          SetTimearr.push(SetTimeattr)
        }
      }
        self.postsaveOrganworkingtime(SetTimearr)

    },
    postsaveOrganworkingtime(SetTimearr) {
      let self = this
      ajax.post({
        url: this.$API.addOrganWorkingTime + self.organId,
        data: { id: self.settimeid, type: self.settimetype, data: JSON.stringify(SetTimearr) },
        success: (response) => {
          this.$message({
            type: "success",
            message: response.message,
          });

        },
      })
    },
    addNew(timeType) {
      let self = this;
      switch (timeType) {
        case "Optime":
          self.OpenTimeArr.push({ startTime: "", endTime: "", dayType: [] });
          break;
        case "Lctime":
          self.LockTimeArr.push({ startTime: "", endTime: "" });
          break;
        // case 'valley':
        // 	self.valleyArr.push({ startTime: '', endTime: '' })
        // break
      }
    },
    deleteItem(timeType, itemIndex) {
      switch (timeType) {
        case "Optime":
          this.OpenTimeArr.splice(itemIndex, 1);
          break;
        case "Lctime":
          this.LockTimeArr.splice(itemIndex, 1);
          break;
      }
    },

    showPTable2(row, column, event, cell) {

      if (column.label == '日增长率') {
        this.outlets = row.outlets;
        this.dialogPersonVisiblex = true
      }


    },

    cilkerow(data) {
      this.$store.dispatch("actions/setisMapAction", true);
      this.$store.dispatch(
        "actions/setfilialeAction",
        getParents(this.FilialeOrganAreaData, data.id).slice(-2)[0]
      );

      setTimeout(() => {
        this.area = data;

        this.$store.dispatch("actions/setisMapAction", false);
        this.updatastate = false;
        this.prothreshold=false
      }, 1);
      this.$refs.filialeOrganAreaTree.setCurrentKey(data.id);

    },
    // 设置唯一ID
    setNodeKey(data) {
      if (data) {
        data.forEach(item => {
          item.type = 'area'
          this.aaa(item)
        })
      }
      return data
    },
    // 递归
    aaa(item) {
      let children = item.children
      children.forEach(i => {
        i.type = 'area'
        this.aaa(i)
      })
    },

    //导出数据
    getExcel() {
      let self = this;
      self.FilialeAreaData = this.FilialeOrganAreaData;
      self.Excelorganid = this.organId;
      self.dialogExcelVisible = true;
      //window.open(this.$API.getExcel2 + id , "_blank");
    },
    ExcelSubmitBtn() {
      let self = this;
      let probeType = self.checkList.join("_")
      let startDate = self.getExceltime[0]
      let endDate = self.getExceltime[1]
      if (this.getExceltype == 0) {
        window.open(this.$API.getReportByOrganIdByMonth +`?month=${self.getExcelmonth}&organId=${self.Excelorganid}&probeTypeList=${self.getExcelradio}`, "_blank");

      }
      else {

        let id = (this.$refs.filialeAreaTree.getCheckedKeys()).join("_")
        window.open(this.$API.exportEleByArea + `?id=${id}&probeType=${probeType}&startDate=${startDate}&endDate=${endDate}`, "_blank");
      }

    },
    // 获取通道类型数据
    getTargetCategoryData() {
      let channelTargetCategory = dictProbeKindList;
      channelTargetCategory.forEach((item) => {

        this.channelTargetCategory.push(item);
        this.checkList.push(item.code);
      });
    },
  },
  watch: {
    filterText(val) {
      this.$refs.refDeviceTree.filter(val);
    },
  },
};

function getParents(data, id) {
  for (var i in data) {
    if (data[i].id == id) {
      return [data[i].id];
    }
    if (data[i].children) {
      var ro = getParents(data[i].children, id);
      if (ro !== undefined) {
        return ro.concat(data[i].id);
      }
    }
  }
}
function getFormatDate(nowDate) {
  let date = new Date(nowDate)
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  let hours = date.getHours()
  let minutes = date.getMinutes()
  let seconds = date.getSeconds()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate < 10) {
    strDate = '0' + strDate
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minutes < 10) {
    minutes = '0' + minutes
  }
  if (seconds < 10) {
    seconds = '0' + seconds
  }
  let currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ':' + minutes + ':' + seconds
  // console.log(currentDate)
  return currentDate
}
</script>

<style lang="stylus" type="text/stylus" scoped>
$adminH = 10.1rem;
$sideW = 3.94rem;
$titleW = 3.85rem;
$areaTreeW = 3.8rem;

.admin-container {
  width: 100%;
  height: 100%;

  .admin-sidebar {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: $sideW;
    height: 100%;
  }

  .admin-main {
    position: absolute;
    top: 0;
    left: $sideW;
    right: 0;
    bottom: 0;
    height: $adminH;
    padding: 0.05rem 0.05rem 0.05rem 0.09rem;
    border-left: solid 0.01rem #99ccff;
    box-sizing: border-box;

    &::after {
      content: '';
      position: absolute;
      left: 0.01rem;
      top: 0;
      height: 100%;
      border-left: 0.01rem solid #0d195a;
    }
  }

  // 标题
  .admin-title-box {
    width: 100%;
    height: 0.5rem;
    background-color: #0d2c5a !important;
    box-shadow: inset 0px 5px 20px 0px rgba(80, 160, 191, 0.3);

    &:hover {
      cursor: pointer;
    }

    .title-icon {
      width: 0.48rem;
      height: 0.48rem;
      margin-left: 0.15rem;
      vertical-align: middle;
    }

    .title-txt {
      font-size: 0.16rem;
      margin-left: 0.1rem;
    }
  }

  // 区域树
  .area-tree-section {
    position: relative;
    width: $areaTreeW;
    margin: 0.1rem 0.1rem 0 0.05rem;
    height: 9.94rem;
    background-image: url('/shike3k-web/img/grid.3486a24c.png');

    .tree-search {
      margin-top: 0.1rem;
      padding: 0 0.2rem;
      display: flex;
      flex-direction: column;
      >>> {
        .el-input>.el-input__inner {
          background-color: rgba(208, 210, 211, 0.2);
          color: #fff;
          height: 0.35rem;
        }
        .el-button--medium {
          padding: 0.1rem 0.1rem;
          //margin-left: 10px;
        }
      }
    }
  }

  // 安装设备数统计
  .device-statistics-section {
    position: relative;
    width: $areaTreeW;
    height: 100%;
    box-sizing: border-box;
  }

  // 地图和用户操作电器部分
  .content-top {
    position: relative;
    min-width: 12rem;
    height: 6.65rem;

    .map-section {
      position: relative;
      width: 100%;
      height: 100%;
    }
  }

  .content-bottom {
    display: flex;
    justify-content: space-between;
    position: relative;
    margin-top: 0.1rem;
    height: 3.25rem;

    .device-statistics-section {
      width: 4.6rem;
      height: 100%;
    }

    .appliance-statistics-section {
      width: 4.6rem;
      height: 100%;
    }

    .appliance-runtime-section {
      width: 5.7rem;
      height: 100%;
    }

    .appliance-switchtimes-section {
      width: 5.7rem;
      height: 100%;
    }
  }
}

.filiale-organ-area-tree {
  cursor: pointer;
}
.aerialview-row {
  position: absolute;
  top: 0;
  left: 3.94rem;
  right: 0;
  bottom: 0;
  height: 10.1rem;
  padding: 0.05rem 0.05rem 0.05rem 0.09rem;
  border-left: solid 0.01rem #9cf;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.area-plan-wrap {
  position: absolute;
  top: 0;
  left: 3.94rem;
  right: 0;
  bottom: 0;
  height: 10.1rem;
  padding: 0.05rem 0.05rem 0.05rem 0.09rem;
  border-left: solid 0.01rem #9cf;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.tl-corner {
  position: absolute;
  width: 0.1rem;
  height: 0.1rem;
  left: -0.01rem;
  top: -0.01rem;
  border-top: 0.01rem solid #fff;
  border-left: 0.01rem solid #fff;
}

.tr-corner {
  width: 0.1rem;
  height: 0.1rem;
  position: absolute;
  right: -0.01rem;
  top: -0.01rem;
  border-top: 0.01rem solid #fff;
  border-right: 0.01rem solid #fff;
}

.bl-corner {
  width: 0.1rem;
  height: 0.1rem;
  position: absolute;
  left: -0.01rem;
  bottom: -0.01rem;
  border-bottom: 0.01rem solid #fff;
  border-left: 0.01rem solid #fff;
}

.br-corner {
  width: 0.1rem;
  height: 0.1rem;
  position: absolute;
  right: -0.01rem;
  bottom: -0.01rem;
  border-bottom: 0.01rem solid #fff;
  border-right: 0.01rem solid #fff;
}

.probe-number-chart, .electric-appliance-chart, .electricity-quantity-chart {
  position: relative;
  height: 3.25rem;
  // width: 4.59rem;
  width:3.49rem;
  margin-right: 0.1rem;
  float: left;
  box-shadow: 1px 1px 5px 0 rgba(0, 0, 0, 0.5), 0 3px 15px 0 rgba(30, 144, 255, 0.4) inset;
  background-image: linear-gradient(
    30deg,
    rgba(22, 33, 77, 0.7) 0%,
    rgba(31, 47, 109, 0.7) 100%
  );
  border: solid 0.01rem #44c7f4;
  box-sizing: border-box;
}

.probe-number-chart {
  // width: 4.59rem;
  //width:3.49rem
  width:calc((100% - 5.69rem) / 2)
}

.electric-appliance-chart {
 // width: 4.59rem;
  //width:3.59rem
  width:calc((100% - 5.69rem) / 2)

}

.electricity-quantity-chart {
  width: 5.69rem;
}

.alarm-event-button {
  position: fixed;
  top: 0.78rem;
  right: 0.22rem;
  z-index: 1;
  display: none;
  width: 1.8rem;
  height: 0.36rem;
  line-height: 0.36rem;
  background-color: rgba(22, 33, 77, 0.56);
  border-radius: 0.05rem;
  color: #fff;
  padding: 0;
  margin: 0;
  font-size: 0.16rem;
  cursor: pointer;
}

.alarm-event-button img {
  width: 0.22rem;
  height: 0.22rem;
  vertical-align: middle;
  margin-left: 0.2rem;
  margin-right: 0.1rem;
  margin-bottom: 0.03rem;
}

>>> {
  .Warning-furniture.alarm-event-dialog .el-dialog {
    width: 6.5rem;
    height: 4rem;
    top: 1rem;
    padding: 0rem;

    .el-dialog__header {
      height: 0.6rem;

      .el-dialog__title {
        width: 2rem;
        height: 0.6rem;
        line-height: 0.7rem;
        font-size: 0.16rem;
        padding: 0;
        box-sizing: border-box;
        top: -0.15rem;
      }
    }

    .el-dialog__body {
      padding: 0;

      .close {
        position: absolute;
        top: 0;
        right: 0px;
        width: 100px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        background-color: #1c2754;
      }
    }
  }

  .Warning-furniture .el-table {
    /* height 3.45rem */
    /* overflow-y auto */
    /* border-bottom none !important */
    .el-table__header {
      background-color: #302737;

      th {
        height: 0.6rem !important;
        line-height: 0.6rem !important;
        /* border-bottom none !important */
        padding: 0;
        text-align: center;
        font-size: 0.16rem;
      }
    }

    .el-table__body-wrapper {
      height: 2.78rem;
      overflow-y: auto;
    }

    td {
      /* border-bottom none !important */
      height: 0.88;
      line-height: 0.88rem;
      text-align: center;
      font-size: 0.16rem;
    }

    tr:nth-child(even) td {
      background-color: #16214d;
    }

    tr:nth-child(odd) td {
      background-color: #1d2858;
    }
  }
}

.updata-btn {
  display: inline-block;
  position: absolute;
  margin-left: 0.56rem;
  width: 0.18rem;
  height: 0.18rem;
  top: 3px;
}

.updata-btn img {
  width: 16px;
  height: 16px;
}

.SetTime-title {
  text-align: center;
  color: #fff;
}

.SetTime-box {
  margin-top: 0.2rem;
  display: flex;

  align-items center {
    -webkit-box-align: center;
  }

  -webkit-align-items: center;
  -ms-flex-align: center;

  span {
    padding: 0 0.1rem;
    color: #fff;
  }
}

.SetTime-addBtn {
  text-align: center;
  margin: 0 0 0.1rem;
}
.worktime {
    display: inline-block;
    position: absolute;
    margin-left: 0.56rem;
    width: 0.18rem;
    height: 0.18rem;
    top: 3px;
}
.worktime img{
       width: 16px;
    height: 16px;
}
.SetTime-boxmian .el-checkbox {
    color: #fff;
    margin-right: 10px;
    min-width: 60px;
}
.SetTime-boxmian {
    margin-bottom: 20px;
    margin-top: 10px;
    border-bottom: 1px dashed #a5a5a5;
    padding-bottom: 20px;
}
.SetTime-boxmian:last-child {
    border-bottom: 0;
    margin-bottom: 0;
}
.SetTimeSubmitBtn{
    text-align: center;
}
::v-deep.el-table thead.is-group th {
    background: #1e3385;
}
::v-deep.cktj {
    position: absolute;
    right: 70px;
    top: 27px;
    z-index: 1;
}
::v-deep.yansi-data-table .el-scrollbar__wrap {
    margin-bottom: 0px !important;
}
.quyue_tbn{cursor: pointer;}
::v-deep.el-tabs {
	border: none !important;
  box-shadow:none !important;
  color:#fff !important;
    .el-tabs__header {
      // width: 15.23rem;
      height:0.5rem;
      margin-top:-0.05rem !important;
      margin-left:-0.08rem !important;
      background-color:#0d2c5a !important;
      border-bottom:solid 0.01rem #0d235a !important;
      box-shadow:inset 0px 5px 20px 0px rgba(80, 160, 191, 0.5);
      box-sizing:border-box;
      .el-tabs__item{
        width 2rem
        height 0.44rem
        line-height 0.44rem
        margin-left 0.08rem !important
        border-radius 5px 5px 0px 0px
        border solid 1px #0d235a !important
        border-bottom 0 !important
        margin-top 0.06rem !important
        color #fff !important
        font-size 0.16rem !important
      }
      .el-tabs__item.is-active{
        background-color #29388a !important
        color #fff !important
      }
    }
    .el-tabs__content{
      background-color #29388a
      padding 0 !important
      overflow visible
      }
      .el-tab-pane{
        padding-top 0.1rem
        }
}

.tree-search .el-select{
  display:block
}

//导出
.Excel-box {
  display: flex;
  margin-bottom: 0.1rem;
}

.Excel-title {
  color: #fff;
  font-size: 0.16rem;
  margin-right: 0.2rem;
  padding-top: 0.1rem;
  min-width: 0.7rem;
}

::v-deep.Excel-box .el-checkbox__label {
  color: #fff;
}
</style>
